package com.fankui.servicemsm.controller;

import com.fankui.commonutils.R;
import com.fankui.servicemsm.service.MsmService;
import com.fankui.servicemsm.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * ClassName MsmController
 * Description TODO
 * Date 2023/12/6 13:12
 *
 * @Author 范奎
 * @Since JDK 11
 */
@Api(description = "短信服务")
@RestController
@RequestMapping("/msmservice")
public class MsmController {
    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @ApiOperation(value = "发送验证码")
    @GetMapping("send/{phone}")
    public R sendMsm(@ApiParam(name = "phone", value = "手机号", required = true) @PathVariable String phone) {
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return R.ok();
        }
        code = RandomUtil.getSixBitRandom();
        Map<String, Object> param = new HashMap<>();
        param.put("code", code);
        boolean isSend = msmService.send(param, phone);
        if (isSend) {
            redisTemplate.opsForValue().set(phone, code, 5L, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("验证码发送失败！");
        }
    }
}
